using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using FirstTea.Application.Interfaces;
using FirstTea.Application.Services;
using FirstTea.Infrastructure.Repositories;
using Microsoft.EntityFrameworkCore;
using FirstTea.Infrastructure;
// 如有 Infrastructure 层日志服务，添加如下 using
// using FirstTea.Infrastructure.Logging;
var builder = WebApplication.CreateBuilder(args);

// 注册控制器
builder.Services.AddControllers();

// 自动补充 CORS 配置，允许前端跨域访问（如 Vue3 默认端口 http://localhost:5173）
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowFrontend",
        policy => policy.WithOrigins("http://localhost:5173")
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials());
});

// 注册Swagger/OpenAPI
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo { Title = "FirstTea API", Version = "v1" });
    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme. Example: 'Bearer {token}'",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });
    options.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
});

// 注册分层架构服务
builder.Services.AddScoped<FirstTea.Application.Interfaces.IUserService, FirstTea.Application.Services.UserService>();
builder.Services.AddScoped<FirstTea.Application.Interfaces.IAuthService, FirstTea.Application.Services.AuthService>();
builder.Services.AddScoped<FirstTea.Application.Interfaces.ITeaService, FirstTea.Application.Services.TeaService>();
builder.Services.AddScoped<FirstTea.Application.Interfaces.IOrderService, FirstTea.Application.Services.OrderService>();
builder.Services.AddScoped<FirstTea.Application.Interfaces.IConversationService, FirstTea.Application.Services.ConversationService>();

// 注册日志服务
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IAuthService, AuthService>(); 
builder.Services.AddScoped<ITeaService, TeaService>();
builder.Services.AddScoped<IOrderService, OrderService>();  
builder.Services.AddScoped<IConversationService, ConversationService>();
// builder.Services.AddSingleton<ILogService, ConsoleLogService>(); // 如有日志服务可取消注释

// JWT认证配置（示例，需完善密钥等）
// builder.Services.AddAuthentication(options =>
// {
//     options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
//     options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
// })
// .AddJwtBearer(options =>
// {
//     options.TokenValidationParameters = new TokenValidationParameters
//     {
//         ValidateIssuer = false,
//         ValidateAudience = false,
//         ValidateLifetime = true,
//         ValidateIssuerSigningKey = true,
//         IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourJwtSecretKey"))
//     };
// });

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "FirstTea",
            ValidAudience = "FirstTeaUser",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSuperSecretKey123!"))
        };
    });

builder.Services.AddScoped(typeof(FirstTea.Domain.Repositories.IRepository<>), typeof(FirstTea.Infrastructure.Repositories.EfRepository<>));
builder.Services.AddDbContext<FirstTeaDbContext>(options =>
    options.UseMySql(
        builder.Configuration.GetConnectionString("DefaultConnection") ?? "server=localhost;database=firsttea;user=root;password=123456",
        new MySqlServerVersion(new Version(8, 0, 36))
    )
);

var app = builder.Build();

// 开发环境启用Swagger
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "FirstTea API V1");
        options.RoutePrefix = string.Empty;
    });
}


// 启用 CORS，必须在 UseAuthentication 之前
app.UseCors("AllowFrontend");

// 启用认证（如启用JWT）
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();
